<template>
  <el-card>
    <!-- 工具栏 -->
    <div class="tools-container">
      <div class="buttons">
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleBindClick">添加新测量组</el-button>
      </div>
      <div class="tags">
        <el-button size="mini" icon="el-icon-refresh" circle @click="handleRefreshClick" />
      </div>
    </div>
    <div style="display: flex;align-items: center;font-size: 12px;font-weight: 600">
      <p style="margin-left:30px;">测量点</p>
      <p style="margin-left:200px;">固定点</p>
    </div>
    <el-tabs
      v-model="activeName"
      tab-position="left"
      style="height: 200px;"
      @tab-click="handleTabClick"
    >
      <el-tab-pane
        v-for="(item, index) in baseList"
        :name="'sel' + index"
        :key="item.id"
        :label="'' + item.name + ' (' + item.alias + ') ' + ' [' + item.did + '] '"
        :value="'' + item.id"
      >
        <!-- 表格 -->
        <el-table
          v-loading="listLoading"
          ref="table"
          :data="list"
          height="200"
          class="table-container"
          element-loading-text="加载中..."
          border
          fit
          highlight-current-row
          size="mini"
        >
          <el-table-column type="index" width="50" label="序号" />
          <el-table-column
            v-for="(value, key) in columns"
            v-if="value.show"
            :key="key"
            :label="value.label"
            :prop="key"
            sortable
          />
          <el-table-column align="center" label="启用状态" width="200">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mstatus"
                :active-value="0"
                :inactive-value="1"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="handleChangeStatus(scope.row ,item.id)"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="200">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleEditIssued(scope.row, item.id)"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleUnBindClick(item.id , scope.row, index)"
              >删除</el-button>
            </template>
          </el-table-column>·
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <!-- 修改等级 -->
    <el-dialog title="编辑警报级别" :visible.sync="issuedShow" width="60%">
      <el-form ref="editIssuedForm" :model="editIssuedForm" label-width="100px" :rules="rule">
        <el-form-item label="选择下发时间" prop="levelId">
          <el-select v-model="editIssuedForm.levelId" placeholder="选择指令下发等级">
            <el-option
              v-for="item in issuedList"
              :key="item.id"
              :label="item.levelName + '~' + item.dinterval + 's'"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="off1" prop="off1">
          <el-input-number v-model="editIssuedForm.off1" />
        </el-form-item>
        <el-form-item label="off2" prop="off2">
          <el-input-number v-model="editIssuedForm.off2" />
        </el-form-item>
        <el-form-item label="off3" prop="off3">
          <el-input-number v-model="editIssuedForm.off3" />
        </el-form-item>
        <el-form-item label="disoff" prop="disoff">
          <el-input-number v-model="editIssuedForm.disoff" />
        </el-form-item>
        <el-form-item label="discov" prop="discov">
          <el-input-number v-model="editIssuedForm.discov" />
        </el-form-item>
        <el-form-item label="通道数量" prop="channelSum">
          <el-select v-model="editIssuedForm.channelSum" placeholder="请选择" @change="editIssuedForm.channelNum = ''">
            <el-option label="二通道" value="2" />
            <el-option label="三通道" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="通道选择" prop="channelNum">
          <el-select v-model="editIssuedForm.channelNum" placeholder="请选择">
            <el-option v-if="editIssuedForm.channelSum === '2'" label="12" value="12" />
            <el-option v-if="editIssuedForm.channelSum === '2'" label="13" value="13" />
            <el-option v-if="editIssuedForm.channelSum === '2'" label="23" value="23" />
            <el-option v-if="editIssuedForm.channelSum === '3'" label="全通道" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否防抖" prop="antiShake">
          <el-select v-model="editIssuedForm.antiShake" placeholder="请选择">
            <el-option label="开" value="1" />
            <el-option label="关" value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="issuedShow = false">取 消</el-button>
        <el-button type="primary" @click="handleIssued('editIssuedForm')">修 改</el-button>
      </div>
    </el-dialog>
    <!-- 表单 -->
    <create-group v-if="bindShow" :add-show.sync="bindShow" @refresh="refreshTable" :scene="scene" />
  </el-card>
</template>

<script>
import {
  sceneMeasureGroupList,
  deleteMeasureGroup,
  getMeasureGroupBaseList,
  updateMeasureGroup,
} from "@/api/scene";
import { getIssuedList } from "@/api/issued";
import CreateGroup from "./createGroup";
import { check } from "@/utils/check";
import { mapGetters } from "vuex";
const columns = {
  did: {
    label: "绑定中控名称",
    center: true,
    sort: true,
    show: true,
    type: "string",
    disabled: false,
    width: 0,
  },
  name: {
    label: "全称",
    center: true,
    sort: true,
    show: true,
    type: "string",
    disabled: false,
    width: 0,
    rule: () => {
      return new Error();
    },
  },
  alias: {
    label: "简称",
    center: true,
    sort: true,
    show: true,
    type: "string",
    disabled: false,
    width: 0,
  },
  levelName: {
    label: "等级",
    center: true,
    sort: false,
    show: true,
    type: "string",
    disabled: false,
    width: 0,
  },
  did: {
    label: "设备ID",
    center: true,
    sort: false,
    show: true,
    type: "date",
    disabled: true,
    width: 0,
  },
};
export default {
  components: {
    CreateGroup,
  },
  props: {
    scene: {
      type: Number,
      default: -1,
    },
  },
  data() {
    return {
      list: null,
      listLoading: true,
      listQuery: {
        scene: this.scene,
        tran: 0,
      },
      baseList: [], // 基准点list
      total: 0,
      searchShow: false,
      bindShow: false,
      headerShow: false,
      isIndeterminate: true,
      checkAll: true,
      columns: [],
      row: {},
      checkAdd: false,
      checkStatus: false,
      checkDetele: false,
      activeName: "sel0",
      nowTabIndex: "0",
      issuedShow: false,
      issuedList: [],
      editIssuedForm: {
        levelId: "",
        off1: "",
        off2: "",
        off3: "",
        disoff: "",
        discov: "",
        channelSum: '',
        channelNum: '',
        antiShake: '',
      },
      rule: {
        levelId: [
          { required: true, message: "请选择警报等级", trigger: "change" },
        ],
        off1: [{ required: true, message: "请输入off1", trigger: "blur" }],
        off2: [{ required: true, message: "请输入off2", trigger: "blur" }],
        off3: [{ required: true, message: "请输入off3", trigger: "blur" }],
        disoff: [{ required: true, message: "请输入disoff", trigger: "blur" }],
        discov: [{ required: true, message: "请输入discov", trigger: "blur" }],
        channelSum: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        channelNum: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        antiShake: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      },
    };
  },
  computed: {
    // ...mapGetters([
    //   'roles'
    // ]),
    header: {
      set: function (v) {
        Object.keys(this.columns).forEach((key) => {
          this.columns[key].show = false;
          v.forEach((i) => {
            if (key === i) {
              this.columns[key].show = true;
            }
          });
        });
        const checkedCount = v.length;
        this.checkAll = checkedCount === Object.keys(this.columns).length;
        console.log(this.checkAll);
        this.isIndeterminate =
          checkedCount > 0 && checkedCount < Object.keys(this.columns).length;
        console.log(
          this.isIndeterminate,
          v.length,
          Object.keys(this.columns).length
        );
        return Object.keys(this.columns).filter((i) => this.columns[i].show);
      },
      get: function () {
        var array = Object.keys(this.columns).filter(
          (i) => this.columns[i].show
        );
        return array;
      },
    },
  },
  mounted() {
    // check(this.roles, ['添加测量组设备', '更改测量组启用状态', '删除测量组'], (list) => {
    //   this.checkAdd = list[0]
    //   this.checkStatus = list[1]
    //   this.checkDetele = list[2]
    // })
    this.fetchBaseList();
    this.columns = columns;
    var checkedCount = this.header.length;
    this.checkAll = checkedCount === Object.keys(this.columns).length;
    this.isIndeterminate =
      checkedCount > 0 && checkedCount < Object.keys(this.columns).length;
    getIssuedList({ sceneId: this.$route.params.id }).then((res) => {
      this.issuedList = res.data;
    });
  },
  methods: {
    fetchData() {
      this.listLoading = true;
      sceneMeasureGroupList(this.listQuery).then((response) => {
        this.list = response.data;
        this.listLoading = false;
      });
    },
    // <<<< 工具栏相关
    handleCheckAllChange(val) {
      this.header = val ? Object.keys(this.columns) : [];
      Object.keys(this.columns).forEach((key) => {
        this.columns[key].show = val;
      });
      this.isIndeterminate = false;
    },
    handleRefreshClick() {
      this.$message({
        message: "刷新成功",
        type: "success",
        duration: 800,
      });
      this.fetchBaseList(Number(this.nowTabIndex));
    },
    handleSearchShowChange() {
      this.searchShow = !this.searchShow;
    },
    handleBindClick() {
      this.bindShow = true;
      this.row = {};
    },
    refreshTable() {
      this.fetchBaseList(Number(this.nowTabIndex));
    },
    // >>>> 工具栏相关

    // <<<< 表头相关

    // >>>> 表头相关

    // <<<< 表格相关
    handleUnBindClick(tranId, row, index) {
      this.$confirm("此操作将解绑该设备, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteMeasureGroup({ tranId, receId: row.id }).then((res) => {
            if (res.ok) {
              this.$message({
                message: res.msg,
                type: "success",
                duration: 800,
              });
              this.fetchBaseList(index);
            } else {
              this.$message({
                message: res.msg,
                type: "success",
                duration: 800,
              });
            }
          });
        })
        .catch(() => {
          console.log("取消解绑");
        });
    },
    handleBeforeClose(done) {
      this.bindShow = false;
      done();
    },
    // >>>> 表格相关

    // 获取基准点信息
    fetchBaseList(index = 0) {
      getMeasureGroupBaseList({ scene: this.scene }).then((res) => {
        this.baseList = res.data;
        if (res.data.length > 0) {
          this.listQuery.tran = res.data[index].id;
          console.log(this.listQuery.tran);
          this.fetchData();
        }
      });
    },
    // 点击tab触发
    handleTabClick(tab) {
      this.listQuery.tran = this.baseList[tab.index].id;
      this.nowTabIndex = tab.index;
      this.fetchData();
    },
    // switch 改变状态
    handleChangeStatus(data, id) {
      updateMeasureGroup({
        receId: data.id,
        tranId: id,
        status: data.mstatus,
        off1: data.off1,
        off2: data.off2,
        off3: data.off3,
        disoff: data.disoff,
        discov: data.discov,
        channelSum: data.channelSum,
        channelNum: data.channelNum,
        antiShake: data.antiShake
      }).then((res) => {
        console.log(res);
        if (res.ok) {
          this.$message({
            message: res.data,
            type: "success",
            duration: 800,
          });
        }
      });
    },
    // 修改级别显示弹框
    handleEditIssued(data, id) {
      this.issuedShow = true;
      this.editIssuedForm = {
        levelId: data.level,
        receId: data.id,
        tranId: id,
        off1: data.off1,
        off2: data.off2,
        off3: data.off3,
        disoff: data.disoff,
        discov: data.discov,
        channelSum: String(data.channelSum),
        channelNum: String(data.channelNum),
        antiShake: String(data.antiShake)
      };
    },
    // 修改提交
    handleIssued(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const {
            levelId,
            receId,
            tranId,
            off1,
            off2,
            off3,
            disoff,
            discov,
            channelSum, 
            channelNum, 
            antiShake
          } = this.editIssuedForm;
          updateMeasureGroup({
            levelId,
            receId,
            tranId,
            off1,
            off2,
            off3,
            disoff,
            discov,
            channelSum: Number(channelSum),
            channelNum: Number(channelNum),
            antiShake: Number(antiShake)
          }).then((res) => {
            if (res.ok) {
              this.$message({
                message: res.data,
                type: "success",
                duration: 800,
              });
              this.issuedShow = false;
              this.fetchData();
            }
          });
        }
      });
    },
  },
};
</script>

